#include <pthread.h>
#include <iostream>
using namespace std;

int board = 0;
pthread_rwlock_t rw;

void *reader(void *args)
{
    const char *name = static_cast<const char *>(args);
    while (true)
    {
        pthread_rwlock_rdlock(&rw);
        cout << "reader read:" << board << endl;
        pthread_rwlock_unlock(&rw);
    }
}

void *writer(void *args)
{
    const char *name = static_cast<const char *>(args);
    while (true)
    {
        pthread_rwlock_wrlock(&rw);
        board++;
        cout << "I am writer" << endl;
        pthread_rwlock_unlock(&rw);
    }
}

int main()
{
    pthread_rwlock_init(&rw, nullptr);

    pthread_t r1, r2, r3, r4, r5, w;
    pthread_create(&r1, nullptr, reader, (void *)"reader1");
    pthread_create(&r2, nullptr, reader, (void *)"reader2");
    pthread_create(&r3, nullptr, reader, (void *)"reader3");
    pthread_create(&r4, nullptr, reader, (void *)"reader4");
    pthread_create(&r5, nullptr, reader, (void *)"reader5");
    pthread_create(&w, nullptr, writer, (void *)"writer");

    pthread_join(r1, nullptr);
    pthread_join(r2, nullptr);
    pthread_join(r3, nullptr);
    pthread_join(r4, nullptr);
    pthread_join(r5, nullptr);
    pthread_join(w, nullptr);

    pthread_rwlock_destroy(&rw);
    return 0;
}